/**
 * Comment View Component
 * 评论查看和筛选组件
 */
import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  List, 
  Card, 
  Tag, 
  Space, 
  Button, 
  Checkbox, 
  Radio,
  Statistic,
  Row,
  Col,
  Typography,
  message,
  Spin
} from 'antd';
import { 
  LikeOutlined, 
  CommentOutlined,
  SmileOutlined,
  FrownOutlined,
  MehOutlined,
  CheckOutlined
} from '@ant-design/icons';
import { generationService } from '../../../services/generation.service';
import styles from './style.module.css';

const { Text, Paragraph } = Typography;

interface Comment {
  id?: string;
  content: string;
  author: string;
  likes: number;
  sentiment?: 'positive' | 'negative' | 'neutral';
  quality_score?: number;
  relevance_score?: number;
  selected?: boolean;
}

interface CommentViewProps {
  visible: boolean;
  topic: {
    title: string;
    comments?: Comment[];
  };
  onClose: () => void;
  onUseComments: (comments: Comment[]) => void;
}

const CommentView: React.FC<CommentViewProps> = ({
  visible,
  topic,
  onClose,
  onUseComments
}) => {
  const [loading, setLoading] = useState(false);
  const [processedComments, setProcessedComments] = useState<Comment[]>([]);
  const [selectedComments, setSelectedComments] = useState<Set<string>>(new Set());
  const [filterSentiment, setFilterSentiment] = useState<string>('all');
  const [sentimentStats, setSentimentStats] = useState({
    positive: 0,
    negative: 0,
    neutral: 0
  });

  useEffect(() => {
    if (visible && topic.comments && topic.comments.length > 0) {
      analyzeComments();
    }
  }, [visible, topic]);

  // 分析评论
  const analyzeComments = async () => {
    if (!topic.comments || topic.comments.length === 0) return;

    setLoading(true);
    try {
      const result = await generationService.analyzeComments({
        comments: topic.comments,
        topic_keywords: [topic.title]
      });

      // 设置处理后的评论
      const processed = result.top_comments.map((comment: any, index: number) => ({
        ...comment,
        id: `comment_${index}`,
        selected: false
      }));
      
      setProcessedComments(processed);
      
      // 设置情感统计
      setSentimentStats({
        positive: Math.round(result.sentiment_distribution.positive),
        negative: Math.round(result.sentiment_distribution.negative),
        neutral: Math.round(result.sentiment_distribution.neutral)
      });
    } catch (error) {
      console.error('Failed to analyze comments:', error);
      message.error('评论分析失败');
      // 使用原始评论
      const fallback = topic.comments.map((c, i) => ({
        ...c,
        id: `comment_${i}`,
        sentiment: 'neutral' as const,
        selected: false
      }));
      setProcessedComments(fallback);
    } finally {
      setLoading(false);
    }
  };

  // 切换评论选择
  const toggleCommentSelection = (commentId: string) => {
    const newSelected = new Set(selectedComments);
    if (newSelected.has(commentId)) {
      newSelected.delete(commentId);
    } else {
      newSelected.add(commentId);
    }
    setSelectedComments(newSelected);
  };

  // 获取情感图标
  const getSentimentIcon = (sentiment?: string) => {
    switch (sentiment) {
      case 'positive':
        return <SmileOutlined style={{ color: '#52c41a' }} />;
      case 'negative':
        return <FrownOutlined style={{ color: '#ff4d4f' }} />;
      case 'neutral':
      default:
        return <MehOutlined style={{ color: '#faad14' }} />;
    }
  };

  // 获取情感标签颜色
  const getSentimentColor = (sentiment?: string) => {
    switch (sentiment) {
      case 'positive':
        return 'green';
      case 'negative':
        return 'red';
      case 'neutral':
      default:
        return 'orange';
    }
  };

  // 筛选评论
  const getFilteredComments = () => {
    if (filterSentiment === 'all') {
      return processedComments;
    }
    return processedComments.filter(c => c.sentiment === filterSentiment);
  };

  // 使用选中的评论
  const handleUseSelected = () => {
    const selected = processedComments.filter(c => c.id && selectedComments.has(c.id));
    if (selected.length === 0) {
      message.warning('请至少选择一条评论');
      return;
    }
    onUseComments(selected);
  };

  return (
    <Modal
      title={`评论分析 - ${topic.title}`}
      visible={visible}
      onCancel={onClose}
      width={800}
      footer={[
        <Button key="cancel" onClick={onClose}>
          取消
        </Button>,
        <Button 
          key="use" 
          type="primary" 
          icon={<CheckOutlined />}
          onClick={handleUseSelected}
          disabled={selectedComments.size === 0}
        >
          使用选中评论 ({selectedComments.size})
        </Button>
      ]}
    >
      <Spin spinning={loading}>
        {/* 情感统计 */}
        <Card className={styles.statsCard} size="small">
          <Row gutter={16}>
            <Col span={8}>
              <Statistic
                title="正面评论"
                value={sentimentStats.positive}
                suffix="%"
                valueStyle={{ color: '#52c41a' }}
                prefix={<SmileOutlined />}
              />
            </Col>
            <Col span={8}>
              <Statistic
                title="中性评论"
                value={sentimentStats.neutral}
                suffix="%"
                valueStyle={{ color: '#faad14' }}
                prefix={<MehOutlined />}
              />
            </Col>
            <Col span={8}>
              <Statistic
                title="负面评论"
                value={sentimentStats.negative}
                suffix="%"
                valueStyle={{ color: '#ff4d4f' }}
                prefix={<FrownOutlined />}
              />
            </Col>
          </Row>
        </Card>

        {/* 筛选器 */}
        <div className={styles.filterBar}>
          <Radio.Group 
            value={filterSentiment} 
            onChange={e => setFilterSentiment(e.target.value)}
          >
            <Radio.Button value="all">全部</Radio.Button>
            <Radio.Button value="positive">
              <SmileOutlined /> 正面
            </Radio.Button>
            <Radio.Button value="neutral">
              <MehOutlined /> 中性
            </Radio.Button>
            <Radio.Button value="negative">
              <FrownOutlined /> 负面
            </Radio.Button>
          </Radio.Group>
        </div>

        {/* 评论列表 */}
        <List
          className={styles.commentList}
          dataSource={getFilteredComments()}
          renderItem={comment => (
            <List.Item
              key={comment.id}
              actions={[
                <Space>
                  <span><LikeOutlined /> {comment.likes}</span>
                </Space>
              ]}
              extra={
                <Checkbox
                  checked={comment.id ? selectedComments.has(comment.id) : false}
                  onChange={() => comment.id && toggleCommentSelection(comment.id)}
                />
              }
            >
              <List.Item.Meta
                avatar={getSentimentIcon(comment.sentiment)}
                title={
                  <Space>
                    <Text strong>{comment.author}</Text>
                    <Tag color={getSentimentColor(comment.sentiment)}>
                      {comment.sentiment === 'positive' ? '正面' :
                       comment.sentiment === 'negative' ? '负面' : '中性'}
                    </Tag>
                    {comment.quality_score && comment.quality_score > 0.7 && (
                      <Tag color="gold">高质量</Tag>
                    )}
                  </Space>
                }
                description={
                  <div>
                    <Paragraph 
                      ellipsis={{ rows: 3, expandable: true }} 
                      className={styles.commentContent}
                    >
                      {comment.content}
                    </Paragraph>
                    {comment.quality_score && (
                      <Space size="small" style={{ marginTop: 8 }}>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          质量分: {(comment.quality_score * 100).toFixed(0)}%
                        </Text>
                        {comment.relevance_score && (
                          <Text type="secondary" style={{ fontSize: 12 }}>
                            相关度: {(comment.relevance_score * 100).toFixed(0)}%
                          </Text>
                        )}
                      </Space>
                    )}
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Spin>
    </Modal>
  );
};

export default CommentView;